package com.base.controller.utils;

import com.alibaba.fastjson.JSONObject;
import com.base.exception.CustomException;
import com.base.utils.StringUtil;
import com.base.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.jdbc.Null;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 猎户座接口对接
 */
public class OrionUtil {


     static Logger logger= LoggerFactory.getLogger(OrionUtil.class);

    private final static CloseableHttpClient httpClient = HttpClients.createDefault();

    private static final String server = "http://ec2-3-35-216-114.ap-northeast-2.compute.amazonaws.com:8023/";
    // 获取用户信息接口
    private static final String USERINFO_URL = server + "api/v1/mall/userinfo";
    // 用户注册接口
    private static final String REGISTER_URL = server + "api/v1/mall/register";
    // 获取验证码接口
    private static final String SENDSMS_URL = server + "api/v1/mall/sendsms";
    // 登录接口
    private static final String LOGIN_URL = server + "api/v1/mall/grouplogin";
    /**
     * 获取登录用户
     */
    public static JSONObject getUserInfo(String username){
        HttpPost httpPost = new HttpPost(USERINFO_URL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username",username));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            logger.info(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity, "utf-8");
            if (StringUtils.isNull(data)){
                throw new CustomException("猎户座获取用户信息接口调用失败");
            }
            logger.info( data );
            return JSONObject.parseObject(data).getJSONObject("data");
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
        return null;
    }

    public  static void registUser(String mobile,String password){
        HttpPost httpPost = new HttpPost(REGISTER_URL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username",mobile));
        params.add(new BasicNameValuePair("phone",mobile));
        params.add(new BasicNameValuePair("area","86"));
        params.add(new BasicNameValuePair("verify",sendSms(mobile)));
        params.add(new BasicNameValuePair("password",password));
        params.add(new BasicNameValuePair("rptPwd",password));
        params.add(new BasicNameValuePair("payPwd","123456"));
        params.add(new BasicNameValuePair("rptPayPwd","123456"));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            logger.info(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity, "utf-8");
            if (StringUtils.isNull(data) ){
                throw new CustomException("猎户座获取用户注册接口调用失败");
            }
            logger.info( data );
            logger.info( "猎户座用户注册:{}" ,JSONObject.parseObject(data).get("message"));
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

    public static String sendSms(String mobile){
        HttpGet httpGet = new HttpGet(SENDSMS_URL+"?phone="+mobile);
        CloseableHttpResponse response = null;
        String data = "";
        try {
            response = httpClient.execute(httpGet);
            logger.info(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            data = EntityUtils.toString(entity, "utf-8");
            if (StringUtils.isNull(data)){
                throw new CustomException("猎户座获取验证码接口调用失败");
            }
            logger.info( data );
            return JSONObject.parseObject(data).getJSONObject("data").getString("code");
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new CustomException(e.getMessage());
        } catch (NullPointerException e){
            String message = JSONObject.parseObject(data).getString("message");
            logger.warn(message);
            throw new CustomException(message);
        }
            finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

    public static boolean login(String username,String password){
        HttpPost httpPost = new HttpPost(LOGIN_URL);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username",username));
        params.add(new BasicNameValuePair("password",password));
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            logger.info(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            String data = EntityUtils.toString(entity, "utf-8");
            if (StringUtils.isNull(data) ){
                throw new CustomException("猎户座获取用户登录接口调用失败");
            }
            logger.info( data );
            logger.info( "猎户座用户登录:{}" ,JSONObject.parseObject(data).get("message"));
            if ("0".equals(JSONObject.parseObject(data).getString("code"))){
                return true;
            }
                return false;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return false;
        } finally {
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }


    public static void main(String[] args) {
      login("13001756710","Aa123456");
    }

}
